package org.hxzon.demo.lucene;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;

public class FirstLuceneDemo {
    public static final Version luceneVersion = Version.LUCENE_34;
    public static final String textToBeIndexed = "This is the text to be indexed.";
    public static final String fieldName = "fieldName";
    public static final String queryString = "text";

    public static void main(String[] args) throws Exception {
        Analyzer analyzer = new StandardAnalyzer(luceneVersion);

        // Store the index in memory:
        Directory indexDirectory = new RAMDirectory();
        // To store an index on disk, use this instead:
        //Directory directory = FSDirectory.open("/tmp/testindex");
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(luceneVersion, analyzer);
        //IndexWriter iwriter = 
        //new IndexWriter(directory, analyzer, true, new IndexWriter.MaxFieldLength(25000));
        IndexWriter indexWriter = new IndexWriter(indexDirectory, indexWriterConfig);
        Document doc = new Document();
        doc.add(new Field(fieldName, textToBeIndexed, Field.Store.YES, Field.Index.ANALYZED));
        indexWriter.addDocument(doc);
        indexWriter.close();

        // Now search the index:
        IndexSearcher indexSearcher = new IndexSearcher(indexDirectory, true); // read-only=true
        // Parse a simple query that searches for "text":
        QueryParser queryParser = new QueryParser(luceneVersion, fieldName, analyzer);
        Query query = queryParser.parse(queryString);
        ScoreDoc[] hits = indexSearcher.search(query, null, 1000).scoreDocs;
        assertEquals(1, hits.length);
        // Iterate through the results:
        for (int i = 0; i < hits.length; i++) {
            Document hitDoc = indexSearcher.doc(hits[i].doc);
            assertEquals(textToBeIndexed, hitDoc.get(fieldName));

        }
        indexSearcher.close();
        indexDirectory.close();
    }

    public static void assertEquals(String a, String b) {
        System.out.println(a.equals(b));
    }

    public static void assertEquals(long a, long b) {
        System.out.println(a == b);
    }
}
